import PublicRouters from "./public-routers";
import HomeRouters from "./home-routers";
import {getLocalStorage} from "../utils";
import {onRouteBeforeRule, RouteObjectRule} from "../react-router-dom6-guard";

const routes: RouteObjectRule[] = [
    {

        path: '*',
        redirect: '/home',
    },
    ...PublicRouters,
    ...HomeRouters,
];

//根据路径获取路由
const checkAuth = (routers: Array<RouteObjectRule>, path: string) => {
    for (const data of routers) {
        if (data.path === path) return data;
        if (data.children) {
            const res = checkAuth(data.children, path);
            if (res) return res;
        }
    }
    return null
};

// 单独的页面需要设置权限等， 根据路径，获取路由的详情
const checkRouterAuth = (path: string) => checkAuth(routes, path);

//全局路由守卫
const onRouteBefore: onRouteBeforeRule = (meta, to) => {
    const {auth, title} = meta;
    if (title) {    // 动态修改页面title
        document.title = title || '统一认证';
    }
    // return to;
    // token权限验证
    return (auth && !getLocalStorage('access_token')) ? '/login' : to;
};

export default routes;

export {
    onRouteBefore,
    checkRouterAuth,
}

